package controller;

import com.root.health.bean.CorrelationInfo;
import com.root.health.bean.ExamInfo;
import com.root.health.bean.UserInfo;
import com.root.health.service.CorrelationService;
import com.root.health.service.ExamService;
import com.root.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Controller
public class ExamController {
    @Autowired
    ExamService examService;
    @Autowired
    UserService userService;
    @Autowired
    CorrelationService correlationService;
    @Autowired
    CorrelationController correlationController;
    @Autowired
    LoginController loginController;
    /**
     *
     * 体检信息添加
     */
    @GetMapping("examinfo")
    public String examPage(){return "examinfo";}
    @PostMapping("examinfoAction")
    public String examPage(UserInfo userInfo, ExamInfo examInfo, HttpSession session, HttpServletRequest request, Model model)throws Exception{
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }
        UserInfo tempo_user = (UserInfo) session.getAttribute("loginUser");
        userInfo = userService.getUserbyName(tempo_user.getUserName());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datestr = request.getParameter("examDateform");
        java.util.Date date = dateFormat.parse(datestr+":00");
        Timestamp time = Timestamp.valueOf(datestr+":00");
        Date dateNow = new Date(System.currentTimeMillis());
        System.out.println("体检日期："+dateNow);
        if(date.getTime()-dateNow.getTime()<0){
            model.addAttribute("errormsg","体检时间错误");
            return "error";
        }
        examInfo.setExamDate(time);
        if(userInfo.getRole().equals("children")){
            session.setAttribute("examInfo",examInfo);
            List<Map<String,Object>> userMapList;
            userMapList = correlationController.ChildrenCorrUser(userInfo);
            model.addAttribute("userMapList",userMapList);
            return "selectuserExam";//如果当前用户为子女账户，则执行查询操作并跳转至选择账户页面
        }else{
            examInfo.setUserId(userInfo.getUserId());
            //将当前用户id放入examInfo的userid中
            examService.examInfo(examInfo.getMain(),examInfo.getExamDate(),examInfo.getExamSite(),examInfo.getUserId());
            model.addAttribute("successHref","selectexaminfo");
            return "success";
        }
    }
    /**
     *
     * 子女账户添加体检信息
     */
    @PostMapping("childrenExamAdd")
    public String childrenExamAdd(){
        return "childrenExamAdd";
    }
    @GetMapping("childrenExamAdd")
    public String childrenExamAdd(String username, ExamInfo examInfo, HttpSession session, HttpServletRequest request, Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }
        session.setAttribute("username",username);
        examInfo = (ExamInfo) session.getAttribute("examInfo");
        examInfo.setUserId(userService.getUserbyName(username).getUserId());
        //System.out.println("childrenExamAdd");
        //将当前用户id放入examInfo的userid中
        if(examService.examCheck(examInfo.getMain(),examInfo.getExamDate(),examInfo.getExamSite(),examInfo.getUserId())==null) {
            examService.examInfo(examInfo.getMain(), examInfo.getExamDate(), examInfo.getExamSite(), examInfo.getUserId());
            model.addAttribute("successHref","selectexaminfo");
            return "success";
        }else{
            model.addAttribute("errormsg","体检信息添加重复");
            return "error";
        }
    }

    /**
     *
     * 体检信息查询
     */
    @PostMapping("selectexaminfo")
    public String selectexaminfo(){
        return "selectexam";
    }
    @GetMapping("selectexaminfo")
    public String selectexaminfo(ExamInfo examInfo,UserInfo userInfo,Model model,HttpSession session){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }
        UserInfo tempo_user = (UserInfo) session.getAttribute("loginUser");
        userInfo = userService.getUserbyName(tempo_user.getUserName());
        //由于Session传递来的用户是前端页面中输入的用户实体类，没有被数据库增加userid，所以需要再从数据库查询一次当前用户获取userid
        List<ExamInfo> examList;
        List<Map<String,Object>> examMapList = new LinkedList<>();
        Map<String,Object> examMap;
        if(userInfo.getRole().equals("parents")){
            examList = examService.examByid(userInfo.getUserId());
            for (int i = 0; i < examList.toArray().length; i++) {
                int finalI = i;
                examMap = new HashMap<>(){{
                    put("main", examList.get(finalI).getMain());
                    put("examDate",examList.get(finalI).getExamDate());
                    put("examSite",examList.get(finalI).getExamSite());
                    put("realName",userService.getUserbyId(examList.get(finalI).getUserId()).getRealname());
                    put("examId",examList.get(finalI).getExamId());
                }};
                examMapList.add(examMap);
            }
            model.addAttribute("examMapList",examMapList);
            return "selectexam";//如果当前用户角色为父母，仅查询该用户的体检信息
        }else{// if(userInfo.getRole().equals("children"))
            //如果当前用户角色为子女，则先从关联信息表查询该角色关联用户id，再以list形式查询对应id的体检信息
            List<CorrelationInfo> list_corr = correlationService.parentidgetByid(userInfo.getUserId());
            for (int i = 0; i < list_corr.toArray().length; i++) {
                if(list_corr.get(i)==null){
                    break;//若本次循环中list_corr不存在，则跳出整个循环防止出现数组越界错误
                }
                List<ExamInfo> a_list = examService.examByid(list_corr.get(i).getParentid());
                //测试System.out.println("a_list:"+a_list+"a_list的长度为:"+a_list.toArray().length);
                for (int j = 0; j < a_list.toArray().length; j++) {
                    if(a_list.get(j)==null){
                        break;//若本次循环中a_list不存在，则跳出整个循环防止出现数组越界错误
                    }
                    int finalJ = j;
                    examMap = new HashMap<>(){{
                        put("main", a_list.get(finalJ).getMain());
                        put("examDate",a_list.get(finalJ).getExamDate());
                        put("examSite",a_list.get(finalJ).getExamSite());
                        put("realName",userService.getUserbyId(a_list.get(finalJ).getUserId()).getRealname());
                        put("examId",a_list.get(finalJ).getExamId());
                    }};
                    examMapList.add(examMap);
                    //将已检索信息放入Map中传入前端（因为userName不在examInfo中，所以需要用Map整合信息
                    //测试System.out.println("第"+j+"个examList是:"+examList.get(j));
                    //nameList.add(userService.getUserbyId(examList.get(j).getUserId()));将当前体检信息中体检人的id进行查询，并将查询后的信息添加到nameList中，给前端页面递交name信息
                }
            }
            model.addAttribute("examMapList",examMapList);
            //model.addAttribute("nameList",nameList);
            return "selectexam";
        }

    }
    /**
     *
     * 从体检信息查询页面携带参数实现删除操作
     */

    @PostMapping("examDel")
    public String medicationLinkDel(){

        return "main";
    }

    @GetMapping("examDel")
    public String healthDel(long examid,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        //examid参数从selectexam页面使用@{/examDel(examid=${exam['examId']})}传递而来
        session.setAttribute("examid",examid);
        examService.examDel(examid);
        model.addAttribute("successHref","selectexaminfo");
        return "success";
    }
    //从药品查询页面携带药品名参数实现删除操作

    /**
     *
     * 修改操作中间方法
     */
    @GetMapping("examLinkUpd")
    public String examLinkUpd(long examid,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        ExamInfo examInfo = examService.examByExamId(examid);
        UserInfo userInfo = userService.getUserbyId(examInfo.getUserId());
        model.addAttribute("userName",userInfo.getRealname());
        session.setAttribute("examid",examid);
        return "examUpd";
    }
    /**
     *
     * 修改体检信息
     */
    @PostMapping("examUpd")
    public String examUpd(ExamInfo examInfo,long examid,HttpSession session,HttpServletRequest request,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        session.setAttribute("examid",examid);
        String datestr = request.getParameter("examDateform");
        Timestamp time = Timestamp.valueOf(datestr+":00");
        examInfo.setExamDate(time);
        //将前端页面选择的时间放入examDate中
        examService.examUpd(examInfo.getMain(),examInfo.getExamDate(),examInfo.getExamSite(),examInfo.getExamState(),examid);
        model.addAttribute("successHref","selectexaminfo");
        return "success";
    }

    /**
     * 完成体检
     * @param examId
     * @param session
     * @param model
     * @return
     */
    @GetMapping("examDone")
    public String examDone(long examId,HttpSession session,Model model){
        try {
            examService.examDone(examId);
            return loginController.mainPage(session,model);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

    }
}
